package com.pft.web.view.activity;


import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.pft.web.R;
import com.pft.web.view.CustomViewFinder;
import com.pft.web.view.baseui.BasePermissionActivity;
import com.pft.web.view.contract.QrCodeContract;
import com.pft.web.view.dialog.ConfirmDialog;
import com.pft.web.view.dialog.DialogManager;
import com.pft.web.view.presenter.QrCodePresenterImp;

import butterknife.BindView;
import butterknife.OnClick;

public class ScanActivity extends BasePermissionActivity implements QrCodeContract.View {

    private static final String TAG = "ScanActivity";
    private static final String SCAN_TYPE = "scan_type"; // 扫描类型
    public static final String RESULT_EXTRA = "result_extra"; // 调用页面传递值的key
    public static final int REQUEST_CAMERA_PERMISSION = 1;


    public static final int REQUEST_CODE = 11111;


    @BindView(R.id.v_light_state_ac)
    View mLightStateImage; // 显示闪光灯打开与否的照片

    @BindView(R.id.txw_light_hint_ac)
    TextView mTxwLightHint; // 提示打开闪光灯的文字

    @BindView(R.id.txw_scan_hint_ac)
    TextView mTxwScanHint; // 扫描页面顶部提示文字

    @BindView(R.id.surface_layout)
    FrameLayout surfaceLayout; // 展示相机图像页面

    @BindView(R.id.scan_frame)
    CustomViewFinder mScanFrameView;


    private String mResultExtraName; // 返回数据

    protected QrCodeContract.Presenter mPresenter;

    private boolean mLightState = false; // 闪光灯开启/关闭

    /**
     * 需要在扫描页面做操作
     *
     * @param context 跳转过来的Activity
     */
    public static void launch(Activity context) {
        Intent intent = new Intent(context, ScanActivity.class);
        context.startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onCreate(Bundle paramBundle) {
        super.onCreate(paramBundle);
        setContentView(R.layout.activity_scan);
    }

    @Override
    protected void initData() {
        mResultExtraName = getIntent().getStringExtra(RESULT_EXTRA);
        initView();

        mPresenter = new QrCodePresenterImp(this);

    }


    private void initView() {


        TextView title = (TextView) findViewById(R.id.txw_title_name);
        title.setText("扫描二维码");

        mTxwScanHint.setText("请将条形码或者二维码放入框内，自动扫描");

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
                    REQUEST_CAMERA_PERMISSION);
        } else {
            setSurfaceView();
        }
    }


    private void setSurfaceView() {
        SurfaceView surfaceView = new SurfaceView(this);
        surfaceLayout.addView(surfaceView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                mPresenter.openCamera();
                mPresenter.setupCamera(surfaceLayout.getWidth(), surfaceLayout.getHeight(),
                        mScanFrameView.getFrameRect(), holder);
                mPresenter.startPreview();
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                try {
                    mPresenter.stopPreview();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    mPresenter.closeCamera();
                }
            }
        });
    }

    @OnClick(R.id.txw_back)
    public void onClickDismiss() {
        closePage();
    }

    @OnClick(R.id.v_light_state_ac)
    public void onClickLight() {
        if (mLightState) {
            // 闪光灯已打开 关闭闪光灯
            mPresenter.flashOff();
            mLightStateImage.setBackgroundResource(R.drawable.ic_scan_light_n_2x);
            mTxwLightHint.setText("轻点开启");
            mLightState = false;
        } else {
            // 闪光灯已关闭 开启闪光灯
            mPresenter.flashOn();
            mLightStateImage.setBackgroundResource(R.drawable.ic_scan_light_p_2x);
            mTxwLightHint.setText("轻点关闭");
            mLightState = true;
        }
    }

    @Override
    public void closePage() {
        finish();
    }

    @Override
    public void openCameraError(Throwable t) {
        DialogManager.showConfirmDialog(this, "检测到您未开启相机访问权限，请前去开启", new ConfirmDialog.OnButtonClickListener() {
            @Override
            public void onConfirm() {
                closePage();
            }

            @Override
            public void onCancel() {

            }
        });

    }

    @Override
    public void displayScanResult(int formatMode, String result) {
        Log.e("result", result);
        scanResult(result);
    }

    /**
     * 二维码扫描结果
     * <p>
     * 把需要的操作在里面写入即可
     *
     * @param resultInfo 二维码扫描信息
     */
    private void scanResult(String resultInfo) {
        Log.d(TAG, "scanResult: " + resultInfo);

        // 需要返回操作
        Intent intent = new Intent();
        intent.putExtra(RESULT_EXTRA, resultInfo);
        ScanActivity.this.setResult(RESULT_OK, intent);

        closePage();
    }

}
